import {Component, Hook, Mut, VueComponent, Link, ComponentProps} from 'vue3-oop'
import {
  DialogReactive,
  NButton,
  NCard,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NTable,
  NTag,
  PaginationProps
} from 'naive-ui'
import styles from './index.module.scss'

import TodoTaskApi from './TodoTaskApi'
import DynaTablePanel from "@/components/panel/DynaTablePanel2";
import ProinstApi from "@/module/main/workflow/ProcessInstListView/ProcessInstApi";

interface IProps {
  maxWidth?:number,
  maxHeight?:number
}
@Component()
export default class Index extends VueComponent<IProps> {
  static defaultProps: ComponentProps<IProps> = {
    maxWidth:{default:800},
    maxHeight:{default:600}
  }

  constructor() {
    super()
  }

  @Mut() state = {
    columns: [
      {
        key: "id",
        title: "ID"
      },{
        key: "processInstanceId",
        title: "流程实例ID"
      },{
        key: "taskDefinitionKey",
        title: "任务定义KEY"
      },{
        key: "assignee",
        title: "受理人"
      },{
        key: "name",
        title: "任务名称"
      },{
        key: "createTime",
        title: "创建时间"
      },{
        key: "executionId",
        title: "执行实例ID"
      },{
        key: "originalAssignee",
        title: "原始受理人"
      },{
        key: "tenantId",
        title: "租户ID"
      },{
        key: "suspensionState",
        title: "暂停状态",
        render: (row:any)=>(row['suspensionState']===true?"是":"否")
      },
      // {
      //   key: "isDeleted",
      //   title: "已删除",
      //   render: (row:any)=>(row['isDeleted']===true?"是":"否")
      // },
      {
        key: "priority",
        title: "优先级"
      },{
        key: "SYS_ROW_ACTIONS",
        title: "操作",
        render: (row:any)=>(<NSpace size="small">
          <NButton onClick={()=>{this.handleShowImage(row);}}>流程图</NButton>
          <NButton onClick={()=>{this.openSubmitDialog(row);}}>提交</NButton>
        </NSpace>)
      }
    ] as any[],
    records: [] as any[],
  }

  private rowKey=(row:any)=>row.id;

  @Mut() pagination = {
    showSizePicker: true,
    pageSizes: [10,20,50,100],
    pageSize: 10,
    page: 1,
    itemCount: 0,
    showQuickJumper: true,
    onUpdatePage: (page:number) => {// 切换页
      this.pagination.page = page;
      this.triggerSearch();
    },
    onUpdatePageSize: (size:number) => {// 切换页大小
      this.pagination.pageSize = size;
      this.pagination.page = 1;
      this.triggerSearch();
    },
    prefix: ()=>(
      <NSpace>
        <NTag >总共 {this.pagination.itemCount} 项</NTag>
      </NSpace>
    )
  } as PaginationProps;

  // 快速搜索
  private handleQuickSearch=(value:string)=>{
    console.log("handleQuickSearch",value);
    this.triggerSearch();
  }

  // 触发查询
  triggerSearch=()=>{
    TodoTaskApi.page({
      params:{},
      page:{size:this.pagination.pageSize,current:this.pagination.page}
    }).then(({data})=>{
      const { page,record } = data;
      this.pagination.itemCount = page.total;
      this.state.records = record;
    })
  }

  // 查看流程图
  private handleShowImage=(row:any)=>{
    ProinstApi.getImage(row.processInstanceId).then((response)=>{
      if(200===response.status){
        const url = URL.createObjectURL(response.data)
        window.$dialog.success({
          showIcon: false, closable: false,
          style:{width:"unset"},
          content:()=>(<NImage alt={"流程图"} src={`${url}`} />)
        })
      }
    }).catch(()=>{
      window.$message.warning("打开流程图失败")
    })
  }

  // 提交流程代办任务
  private openSubmitDialog=(row:any)=>{
    const { id,name } = row;
    const formData = ref({variables:[] as {name:string,value:string}[]}).value;
    const hendleStart=()=>{
      const variables = {} as any;
      formData.variables.forEach((item)=>{
        variables[item.name]=item.value;
      });
      TodoTaskApi.submit({
        params:{
          taskId: id,
          variables: variables
        }
      }).then(({data})=>{
        if(data.success){
          window.$message.success(data.message);
          this.triggerSearch();
        }else{
          window.$notification.warning({
            content:data.message
          })
        }
      })
    }
    const dialog = window.$popUp({
      style: {width:"600px",height:"600px"},
      content:()=>(
        <NCard title={`提交流程待办任务 ${name}`}>
          {{
            default:()=>(
              <NForm labelPlacement={"left"}>
                <NTable size='small'>
                  <thead><tr><th>参数名</th><th>参数值</th><th>操作</th></tr></thead>
                  <tbody>
                  {formData.variables.map((item:any,index)=>{
                    return <tr>
                      <td><NInput value={item.name} onUpdateValue={(value)=>{item.name=value}} /></td>
                      <td><NInput value={item.value} onUpdateValue={(value)=>{item.value=value}} /></td>
                      <td><NButton onClick={()=>{formData.variables.splice(index,1)}}>删除</NButton></td>
                    </tr>
                  })}
                  </tbody>
                </NTable>
              </NForm>
            ),
            footer:()=>(<NSpace>
              <NButton size={"small"} onClick={()=>{formData.variables.push({name:"",value:""})}}>添加</NButton>
              <NButton size={"small"} onClick={()=>{hendleStart();dialog.destroy();}}>确定</NButton>
              <NButton size={"small"} onClick={()=>{dialog.destroy()}}>取消</NButton>
            </NSpace>)
          }}
        </NCard>
      )
    }) as DialogReactive;
  }

  @Hook('Mounted')
  onMounted(){
    this.triggerSearch();
  }

  render() {

    return (
      <DynaTablePanel
        class={[styles.todotask_list_view]}
        icon={"ClipboardTask20Filled"}
        title={"流程待办"}
        showQuickSearch={true}
        showSeniorSearch={true}
        onQuickSearch={this.handleQuickSearch}
        nDataTableProps={{
          rowKey:this.rowKey,
          columns:this.state.columns,
          data:this.state.records,
          pagination:this.pagination,
          maxHeight:this.props.maxHeight as number - 155
        }}
        toolbarActions={[]}
      />
    )
  }

  // render() {
  //
  //   return (
  //     <NCard
  //       class={[styles['todolist']]}
  //       header-style={{padding: '10px'}}
  //       content-style={{padding: '10px'}}
  //     >
  //       <div
  //         class={[styles['toolbar']]}
  //       >
  //         <div class={[styles['toolbar_left']]}><NSpace size="small"><NTag
  //           bordered={false}
  //           size={'large'}
  //           style={{fontSize:'18px'}}
  //           color={{color:'whitesmoke'}}
  //         >
  //           {{ avatar: ()=>(<NIcon><Search/></NIcon>), default: ()=>('流程待办') }}
  //         </NTag></NSpace></div>
  //         <div class={[styles['toolbar_middle']]}><NSpace size="small"></NSpace></div>
  //         <div class={[styles['toolbar_right']]}><NSpace size="small">
  //           <SearchBar
  //             onSearch={this.quickSearch}
  //             value={this.state.searchValue}
  //             showSenior={true}
  //             toggleSenior={this.toggleSForm}
  //           />
  //         </NSpace></div>
  //       </div>
  //       <NDataTable
  //         class={[styles['table']]}
  //         remote
  //         striped
  //
  //         columns={this.state.columns}
  //         rowKey={(row)=>row[this.state.keyColumn]}
  //         data={this.state.records}
  //
  //         rowProps={(row:any)=>{
  //           return {
  //             onClick:(e:MouseEvent)=>{
  //               e.stopPropagation();
  //               console.log('row onClick');
  //             },
  //             onDblclick:(e:MouseEvent)=>{
  //               e.stopPropagation();
  //               console.log('row onDbClick');
  //             }
  //           }
  //         }}
  //
  //         pagination={{
  //           showSizePicker: this.page.sizePicker,
  //           pageSizes: this.page.sizes,
  //           pageSize: this.page.size,
  //           page: this.page.current,
  //           itemCount: this.page.total,
  //           showQuickJumper: this.page.jumper,
  //           onChange: this.page.onChange,
  //           onUpdatePageSize: this.page.onReSize,
  //           prefix: ()=>(
  //             <NSpace>
  //               <NTag >总共 {this.page.total} 项</NTag>
  //               <NTag >已选 {this.state.checked.length} 项</NTag>
  //             </NSpace>
  //           )
  //         }}
  //
  //         {...{
  //           id:'CusTable'
  //         }}
  //       />
  //       <NDrawer
  //         to={'#CusTable'}
  //         class={['mytest']}
  //         placement={'top'}
  //         trap-focus={true}
  //         on-mask-click={this.toggleSForm}
  //         show={this.state.showSForm}
  //         height={300}
  //       >
  //         <NDrawerContent>
  //           {{
  //             default:()=>(<NCard>测试</NCard>),
  //             footer:()=>(
  //               <NSpace size={'small'}>
  //                 <NButton type={'primary'} onClick={()=>{}}>搜索</NButton>
  //                 <NButton onClick={this.toggleSForm}>取消</NButton>
  //               </NSpace>
  //             )
  //           }}
  //         </NDrawerContent>
  //       </NDrawer>
  //       <TodolistSubmit ref='todolistSubmitInst'  />
  //
  //
  //     </NCard>
  //   )
  // }
}
